<template>
    <div>
      <!-- 函数防抖 -->
      <button @click="login">不使用防抖登录</button>
      <button @click="handleLogin">登录</button>
    </div>
</template>
<script setup lang='ts'>
//   没有使用函数防抖
const login = () => {
   console.log('登录中...')
}

// 使用函数防抖1 debounce(fn, delay)
// let timer: number | null = null
// const debounce = (fn: Function, delay: number) => {
//  console.log('timer', timer)
//   if(timer) clearTimeout(timer)
//     timer = setTimeout(() => {
//       fn()
//     }, delay)
// }
// 函数防抖2
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null
  return () => {
    console.log('timer', timer)
     timer && clearTimeout(timer)
     timer = setTimeout(() => {
       fn()
     }, delay)
  }
}

let handleLogin = debounce(login, 500)

// 函数节流 throttle(fn, 1000)
const fn1 = () => {
    console.log(Math.random() * 99)
}
const throttle = (fn: Function, delay: number) => {
  let isThrottle: number | null = null
   return () => {
     if (isThrottle) return
     isThrottle = setTimeout(() => {
        fn()
        isThrottle = null
     }, delay)
   }
    
}

addEventListener('mousemove', throttle(fn1, 1000))


// handleLogin = null
</script>


<style lang='scss' scoped>

</style>